package com.example.apple.ddhr_new.activity.setting;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.apple.ddhr_new.BuildConfig;

import com.example.apple.ddhr_new.activity.widget.Dialog;
import com.example.apple.ddhr_new.utils.CacheUtil;
import com.example.lzbase.BaseActivity;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.lifecycle.ViewModelProvider;
import butterknife.BindView;
import butterknife.OnClick;
import event.MessageEvent;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import utils.ClassUtil;

import com.example.apple.ddhr_new.R;
import com.example.lzbase.BaseViewModel;
import com.example.lzbase.BaseViewModelActivity;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.security.Permission;
import java.util.List;

public abstract class WebViewActivity <VM extends BaseViewModel> extends BaseActivity
{
    protected String mH5Url = "";
    protected String title;
    protected VM viewModel;
    private CompositeDisposable mCompositeDisposable;


    public void addSubscription(Disposable s) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(s);
    }
    /*
     * 网页标题
     * */
    public static final String INTENT_TITLE = "INTENT_TITLE";
    /*
     * 网页URL
     * */
    public static final String INTENT_URL = "INTENT_URL";

    /*
     * webView
     * */
    @BindView(R.id.web)
    BridgeWebView webView;

    @BindView(R.id.progressBar1)
    ProgressBar pg1;

    @Override
    protected int titleText() {
        return R.string.app_name;
    }


    @OnClick(R.id.iv_delete)
    public void close(){

        finish();
    }



    @Override
    protected void created(@Nullable Bundle savedInstanceState) {




        mH5Url = getIntent().getExtras().getString(INTENT_URL);
        title = getIntent().getExtras().getString(INTENT_TITLE);
        setTitleText(title);


        if (TextUtils.isEmpty(mH5Url))
        {
            finish();
            return;
        }
        webView.loadUrl(mH5Url);


        webView.getSettings().setDomStorageEnabled(true);// 打开本地缓存提供JS调用,至关重要
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        webView.getSettings().setAllowFileAccess(true);

        webView.getSettings().setAppCacheEnabled(true);
        String appCachePath = getApplication().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setDatabaseEnabled(true);

        webView.setWebViewClient(new BridgeWebViewClient(webView)
        {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                setTitle(webView.getTitle());

                if (url == null) return true;


                try
                {
                    if (url.startsWith("http:") || url.startsWith("https:"))
                    {
                        view.loadUrl(url);
                        return true;
                    }
                    else
                    {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e)
                {


                    return super.shouldOverrideUrlLoading(webView, url);
                }



            }

            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);



            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url)
            {



                return super.shouldInterceptRequest(view, url);
            }

        });

        //        //辅助WebView处理图片上传操作
        webView.setWebChromeClient(new MyChromeWebClient());
        /**
         * 初始化ViewModel
         */
      initViewModel();

    }
    public void onError(Throwable error) {
        if (null != error.getMessage()) {
            Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            ViewModelProvider viewModelProvider = new ViewModelProvider(this.getViewModelStore(), new ViewModelProvider.AndroidViewModelFactory((this).getApplication()));

            this.viewModel = viewModelProvider.get(viewModelClass);
        }


        if (this.viewModel != null) {
            this.viewModel.error.observe(this, error -> {
                onError(error);
            });
            this.viewModel.progress.observe(this, show -> {

                showLoading(show);
            });
        }


    }
    //自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
    public class MyChromeWebClient extends WebChromeClient
    {



        @Override
        public void onProgressChanged(WebView view, int newProgress)
        {
            // TODO 自动生成的方法存根

            if (newProgress == 100)
            {
                pg1.setVisibility(View.GONE);//加载完网页进度条消失
            }
            else
            {
                pg1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                pg1.setProgress(newProgress);//设置进度值
            }

        }

        // For Android 5.0+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams)
        {


            mUploadCallbackAboveL = filePathCallback;


            String type = fileChooserParams.getAcceptTypes()[0];
            if ("video/*".contains(type))
            {
                recordVideo();
                return true;
            }
            else if ("image/*".contains(type))
            {
                takePhoto();

                return true;
            }
            return onShowFileChooser(webView, filePathCallback, fileChooserParams);
        }
    }
    /**
     * 录像
     */
    private void recordVideo()
    {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }

    /**
     * 拍照
     */
    private void takePhoto()
    {
        if(hasPermission(Manifest.permission.CAMERA)){
            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg"));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            {
                imageUri = FileProvider.getUriForFile(this.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg"));//通过FileProvider创建一个content类型的Uri

            }

        }







    }

    private Uri imageUri;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int PHOTO_REQUEST = 100;
    private final static int VIDEO_REQUEST = 120;
    @Override
    protected int getLayoutId() {
        return  R.layout.activity_web_view;
    }

    @Override
    protected void onDestroy()
    {

        super.onDestroy();
        if (webView != null)
        {
            webView.setWebViewClient(null);
            webView.setWebChromeClient(null);
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webView.clearHistory();
            webView.destroy();
            webView = null;
        }
    }




    @Override
    public void onBackPressed() {
        if ( webView.canGoBack())
        {
            webView.goBack();

        }else {
            super.onBackPressed();
        }

    }

    @Override
    public void onResume()
    {
        super.onResume();
        webView.onResume();
        // ...
    }

    @Override
    public void onPause()
    {
        webView.onPause();
        // ...
        super.onPause();
    }
}
